<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, computed, nextTick } from "vue";
import * as echarts from "echarts";

const chartRef = ref();
let myChart = null;
const props = defineProps<{
  title?: string;
  loading?: boolean;
  data: {
    name?: string;
    unit?: string;
    max?: number;
    min?: number;
    data: number[];
  }[];
  xAxisData?: string[];
}>();
const visible = defineModel("visible");
const lineLoading = computed(() => props.loading);
const warnColor = ["#D54941", "#6D32BA"];
let getLeftData = (minVal, maxVal) => {
  const max = maxVal || 0;
  const min = minVal || 0;
  // 控制分隔条数，
  let diff = max - min;
  return {
    max: max + diff,
    min: min - diff
  };
};
const getCustomData = () => {
  const { data } = props;
  const yAxis = [];
  const series = [];
  const legendData = [];
  const markLine = {
    silent: true,
    symbol: "none",
    data: []
  };
  data.forEach((item, index) => {
    const { name, unit, data: itemData, min, max } = item;
    const NumArr = itemData.filter(item => item !== null);
    const minData = Math.min.apply(Math, NumArr);
    const maxData = Math.max.apply(Math, NumArr);
    const minValue = !(minData > min) ? minData : min;
    const maxValue = !(maxData < max) ? maxData : max;
    let interObj = getLeftData(minValue, maxValue);
    let prevNum;
    const seriesData = itemData.map(num => {
      if (num || num === 0) {
        prevNum = num;
        return num;
      } else {
        return prevNum;
      }
    });
    // 1、yAxis
    yAxis.push({
      name: unit,
      alignTicks: index > 0,
      min: min ? interObj.min : undefined,
      max: max ? interObj.max : undefined,
      type: "value",
      splitLine: {
        lineStyle: {
          color: "rgba(255, 255, 255, 0.25)"
        }
      }
    });
    // 2、series
    series.push({
      name,
      type: "line",
      yAxisIndex: index,
      lineStyle: {
        width: 1
      },
      emphasis: {
        focus: "series"
      },
      markLine: {},
      data: seriesData
    });
    // 3、legendData
    legendData.push(name);
  });
  // 4、markLine
  const markLineItem = { max: data[0]?.max, min: data[0]?.min };

  Object.keys(markLineItem).map((key, ind) => {
    if (markLineItem[key] || markLineItem[key] === 0) {
      markLine.data[ind] = {
        name,
        yAxis: markLineItem[key],
        symbol: "none",
        symbolSize: 0,
        lineStyle: {
          color: warnColor[0]
        },
        animation: false,
        label: {
          position: "insideEndTop",
          color: warnColor[0],
          formatter: () => {
            return `${key}-${markLineItem[key]}`;
          }
        }
      };
    }
  });
  if (series[0]) {
    series[0].markLine = markLine;
  }
  return { yAxis, series, legendData };
};
const handleRender = () => {
  const { xAxisData } = props;
  const { yAxis, series, legendData } = getCustomData();
  const option = {
    color: ["#4786FF", "#FFB266", "#8B8AE6", "#FFA299", "#B88AE7", "#85CFF5"],
    grid: {
      bottom: legendData.length > 1 ? 40 : 20,
      left: 40,
      right: 40,
      containLabel: true
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: "none",
          title: {
            zoom: "区域缩放",
            back: "区域缩放还原"
          }
        },
        restore: {
          title: "还原"
        }
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        animation: false,
        label: {
          backgroundColor: "#505765"
        }
      }
    },
    legend: {
      show: legendData.length > 1,
      data: legendData,
      textStyle: {
        color: "rgba(255, 255, 255, 0.25)"
      },
      bottom: 10
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        axisLine: { onZero: false },
        axisLabel: {
          formatter: value => value.split(" ").join("\n\n")
        },
        data: xAxisData
      }
    ],
    yAxis: yAxis,
    series: series
  };
  try {
    myChart?.setOption({ ...option });
  } catch (error) {}
};
const initChart = () => {
  if (!chartRef.value) {
    return;
  }
  if (myChart) {
    myChart?.dispose();
  }
  myChart = echarts.init(chartRef.value);

  handleRender();
};
onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener("resize", handelResize);
});
onUnmounted(() => {
  myChart?.dispose();
  window.removeEventListener("resize", handelResize);
});
const handelResize = () => {
  if (myChart) {
    myChart.resize();
  }
};
watch([visible, lineLoading, props.data], () => {
  if (visible.value && !lineLoading.value) {
    nextTick(() => {
      initChart();
    });
  } else {
    myChart?.dispose();
  }
});
</script>
<template>
  <px-dialog v-model="visible" class="leader-screen-lines-dialog" width="60%" :title="title">
    <div ref="chartRef" v-loading="loading" class="chart-lines" />
  </px-dialog>
</template>
<style lang="scss">
.leader-screen-lines-dialog {
  background: #193149;

  .px-dialog__header {
    padding: 24px 59px 18px 32px;
  }

  .px-dialog__title {
    font-size: 20px;
    font-weight: 500;
    line-height: 24px;
    color: rgb(255 255 255 / 80%);
  }

  .chart-lines {
    height: 500px;
    background: rgb(255 255 255 / 0%);
    border: 1px solid rgb(255 255 255 / 25%);
  }
}
</style>
